<extend name="Public/base" />

<block name="style" >
    <link href="/am/styles/icon.css?v=20151127" rel="stylesheet" />
    <link href="/am/styles/sys_message.css?v=20151127" rel="stylesheet" />
    <style>
        .user_table{
            border: 1px solid #ddd;
            width: 180px;
        }
        .user_table tr{
            border: 1px solid #dddddd;
            height: 30px;
        }
        .user_table td{
            border: 1px solid #dddddd;
            width: 90px;
            text-align: center;
        }
        .current456{
            color: #FFF;
            background: #5FC03D;
        }
        #nav_des span{
            line-height: 35px;
            font-size:18px;
            padding: 4px 15px 4px 18px;
            cursor: pointer;
        }
        #nav_des span:hover{
         background: #81ce44;
     }

       #nav_desss span{
            line-height: 35px;
            font-size:18px;
            padding: 4px 15px 4px 18px;
            cursor: pointer;
        }
        #nav_desss span:hover{
         background: #81ce44;
     }
 </style>
</block>

<block name="body">
   <!-- 弹窗插件 -->
   <include file="Public:artdialog" />
   <!-- 表单验证插件 -->
   <include file="Public:validform" />
   <include file="Public:aomai_dialog_lay" />
   
   <div class="row">
    <div class="col-md-12">
        <div class="block-web">
        <div class="header">
        <if condition="$edit eq 1">
        <div id="nav_desss"><span id="detail-tab">详细描述</span></div>
      <else/>
         
               <div class="actions_diy">
                <if condition="$blongtype eq 'Group'">
                    <!-- <a href="javascript:;" onclick="_es_openDilogLarge('{:U('add_red')}','添加红冲充值')" class="btn btn-default btn-primary"> -->
                    <a href="javascript:;"  onclick="addgoods(this,'{:U('goodslist',array('blongtype'=>'Group','id'=>$result['packageid']))}')" class="btn btn-default btn-primary">
                        <i class="fa fa-plus"></i>添加拼团商品
                    </a>
                    <else />
                    <a href="javascript:;"  onclick="addgoods(this,'{:U('goodslist',array('blongtype'=>'presell','id'=>$result['packageid']))}')" class="btn btn-default btn-primary">
                        <i class="fa fa-plus"></i>添加预售商品
                    </a>
                </if>
            </div>
            <div id="nav_des">
                <span class="current456">基本信息</span>
                <span id="detail-tab">详细描述</span>
            </div>
     
      </if>
   </div>


        <div class="porlets-content">
           <div id="content">
              <form action="{:U('doGroup')}" method="post" id="form_table" enctype="multipart/form-data">
               <input type="hidden" name="packageid" id="packageid" value="{$result['packageid']}">
               <input type="hidden" name="blongtype" id="select" value="{$blongtype}">
           <if condition="$edit neq 1">    
               <table class="con" style="display:block;">
                <else/>
                <table class="con" style="display:none;">
                </if>
                   <tr>
                    <td class="" style="width:400px;">
                        <div class="form-group">
                            <label class="control-label"><font class="red">*</font>包名称</label>
                            <div class="" style="width:200px;">
                                <input type="text" value="{$result['packagename']}" name="packagename" placeholder="请输入包名称" class="form-control " datatype="*" nullmsg="包名称" />
                                <div class="Validform_checktip"></div>
                            </div>
                        </div> 
                        <div class="form-group">
                            <label class="control-label"><font class="red"></font>开始时间</label>
                            <div class="" style="width:200px;">
                                <input type="text" name="starttime" readonly="readonly" id="start_time" placeholder="请输入开始时间" value="{$result['starttime']}" class="form-control laydate-icon"/>
                                <div class="Validform_checktip"></div>
                            </div>
                        </div>

                        <div class="form-group">
                            <label class="control-label"><font class="red"></font>结束时间</label>
                            <div class="" style="width:200px;">
                                <input type="text" name="endtime" readonly="readonly" id="end_time" placeholder="请输入结束时间" value="{$result['endtime']}" class="form-control laydate-icon"/>
                                <div class="Validform_checktip"></div>
                            </div>
                        </div>
                    </td>
                    <td class="" style="width:400px;">
                      <div class="form-group">
                        <label class="control-label"><font class="red"></font>零售总价格</label>
                        <div class="" style="width:200px;">
                            <input type="number" name="sprice"  value="{$result['sprice']|default='0.00'}" class="form-control" readonly = "readonly"/>
                            <div class="Validform_checktip"></div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label"><font class="red"></font>会员总价格</label>
                        <div class="" style="width:200px;">
                            <input type="number" name="uprice"  value="{$result['uprice']|default='0.00'}" class="form-control" readonly = "readonly"/>
                            <div class="Validform_checktip"></div>
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="control-label"><font class="red"></font>VIP总价格</label>
                        <div class="" style="width:200px;">
                            <input type="number" name="vprice"  value="{$result['vprice']|default='0.00'}" class="form-control" readonly = "readonly"/>
                            <div class="Validform_checktip"></div>
                        </div>
                    </div>
                    <div class="form-group" >
                        <label class="control-label"><font class="red">*</font>是否满员</label>
                        <div class="" style="width:200px;">
                         <empty name="result">
                          <label class="radio-inline">
                            <input type="radio"  name="isaccord" value="1" checked="checked">
                            <span class="custom-radio"></span> 满员
                        </label>
                        <label class="radio-inline">
                            <input type="radio"    name="isaccord" value="0">
                            <span class="custom-radio"></span> 不满员
                        </label>
                        <else/>
                        <if condition="$result['isaccord'] eq 0">
                            <label class="radio-inline">
                                <input type="radio"  name="isaccord" value="1">
                                <span class="custom-radio"></span> 满员
                            </label>
                            <label class="radio-inline">
                                <input type="radio"    name="isaccord" value="0" checked="checked">
                                <span class="custom-radio"></span> 不满员
                            </label>
                        </if>
                        <if condition="$result['isaccord'] eq 1">
                            <label class="radio-inline">
                                <input type="radio"  name="isaccord" value="1" checked="checked">
                                <span class="custom-radio"></span> 满员
                            </label>
                            <label class="radio-inline">
                                <input type="radio"    name="isaccord" value="0">
                                <span class="custom-radio"></span> 不满员
                            </label>
                        </if> 
                    </empty>
                </div>
            </div>
        </td>
        <td style="width:400px;"> 
          <div class="form-group">
            <label class="control-label"><font class="red"></font>最小购买数量</label>
            <div class="" style="width:200px;">
                <input type="number" name="minnumber"  value="{$result['minnumber']|default=1}" class="form-control"/>
                <div class="Validform_checktip"></div>
            </div>
        </div>
        <div class="form-group">
            <label class="control-label"><font class="red"></font>最大购买数量</label>
            <div class="" style="width:200px;">
                <input type="number" name="maxnumber"  value="{$result['maxnumber']|default=1}" class="form-control"/>
                <div class="Validform_checktip"></div>
            </div>
        </div>


        <?php if(isset($result['usertype'])):?>
          <if condition="$result['usertype'] eq 0">
              <div class="form-group">
                <label class="control-label"><font class="red"></font>违约金率</label>
                <div class="" style="width:200px;">
                    <input type="text" name="penalty"  value="{$result['penalty']}" class="form-control"/>
                    <div class="Validform_checktip"></div>
                </div>
            </div>
            <div class="form-group">
                <label class="control-label"><font class="red"></font>提成率</label>
                <div class="" style="width:200px;">
                    <input type="text" name="commission"  value="{$result['commission']}" class="form-control"/>
                    <div class="Validform_checktip"></div>
                </div>
            </div>
        </if>
    <?php endif;?>
</td>
<td>
   <div class="form-group">
    <label class="control-label"><font class="red">*</font>组团人数</label>
    <div class="" style="width:200px;">
        <input type="number" name="total"  placeholder="请输入组团人数" value="{$result['total']|default=1}" class="form-control" datatype="*" nullmsg="请输入组团人数" />
        <div class="Validform_checktip"></div>
    </div>
</div>
<div class="form-group">
    <label class="control-label"><font class="red"></font>组团总个数</label>
    <div class="" style="width:200px;">
        <input type="number" name="groupnumber"  value="{$result['groupnumber']|default=1}" class="form-control"/>
        <div class="Validform_checktip"></div>
    </div>
</div> 
<div class="form-group">
    <label class="control-label"><font class="red"></font>包倍数</label>
    <div class="" style="width:200px;">
        <input type="number" name="multiple"  value="{$result['multiple']|default=10}" class="form-control"/>
        <div class="Validform_checktip"></div>
    </div>
</div> 
<div class="form-group">
    <label class="control-label"><font class="red"></font>包总个数</label>
    <div class="" style="width:200px;">
        <input type="number" name="totalquantity" readonly="true"  value="{$result['totalquantity']}" class="form-control"/>
        <div class="Validform_checktip"></div>
    </div>
</div> 
</td> 
</tr>
</table>

<if condition="$edit neq 1">
<table class="con" style="display:none">
<else/>
<table class="con" style="display:block">
</if>
  <tr>
      <td>
          {$FCKeditor}
      </td>
      <td>
         <volist name="img_list" id="img">
            <div id="gallery_{$img.img_id}" style="float:left; text-align:center; border: 1px solid #DADADA; margin: 4px; padding:2px;">
                <a href="javascript:;" onclick="if (confirm('{$lang.drop_img_confirm}')) dropImg('{$img.img_id}')">[-]</a><br />
                <a href="goods.php?act=show_image&img_url={$img.img_url}" target="_blank">
                    <img src="../{if $img.thumb_url}{$img.thumb_url}{else}{$img.img_url}{/if}" {if $thumb_width neq 0}width="{$thumb_width}"{/if} {if $thumb_height neq 0}height="{$thumb_height}"{/if} border="0" />
                </a>
            </div>
        </volist>
    </td>
    <td width="100px" style="padding-left:25px;">详情图片</td>
    <td style="display:;">

        <div class="upload_shop_img_item">
            <div class="upload_wrp">
                <div class="upload_preview" id="gallery_img">
                    <if condition="$imgs neq null" >
                        <volist name="imgs" id="img">
                            <div class="pics_wrp js_guige_images_unitymain" style="height: 247px;" id="file_{$img.id}">
                                <div class="edit_pic_wrp" style="width: 200px;max-width: 200px;height: 200px;">
                                    <img src="/Public/uploads/{$img.file_name}">
                                    <div class="edit_pic_mask">
                                        <a href="javascript:;" title="点击移除" target="_blank" class="icon18_common del_gray js_delete" onclick="removeThisImg(this,{$img.img_id});"></a>
                                        <a href="/Public/uploads/{$img.file_name}" title="查看原图" target="_blank" class="icon18_common search_gray js_delete"></a>
                                        <input type="hidden" name="gallery_img_pic[]" value="{$img.id}">

                                    </div>

                                </div>
                                <div class="gallery_img_sort">
                                    <label>排序：</label>
                                    <input type="text"  name="img_{$img.img_id}_sort" value="{$img.img_sort}">
                                </div>
                                <input type="hidden" name="img_{$img.img_id}_id" value="{$img.img_id}">
                            </div>
                        </volist>
                    </if>
                </div>
                <div class="upload_box">
                    <div class="upload_area">
                        <a class="create_access_primary"
                        id="js_guige_images_unitysub"
                        title="添加文件"
                        onclick="showGoodsPics('{:U('choosePics')}','上传图片',1)" href="javascript:">
                        <i class="icon20_common add_gray" >上传</i>
                    </a>
                </div>
            </div>
        </div>
    </div>

</td>
</tr>
</table>



</form>
</div>
</div>

<if condition="$edit neq 1">
<div id="load_tb_div" style="padding:10px 0px 30px ;display:block">
<else/>
<div id="load_tb_div" style="padding:10px 0px 30px ;display:none">
</if>

  <div style="border-top:1px solid #dcdcdc;margin:5px 0px;">
    <h3 class="content-header">包商品列表</h3>
</div>
<table class="table table-striped goods_list_table   table-bordered table-condensed">
    <thead>
       <tr>

          <th class="opth140">商品名称</th>
          <th class="opth40">商品数量</th>
          <th class="opth40">零售价格</th>
          <th class="opth40">会员价格</th>
          <th class="opth40">VIP价格</th>
          <th class="opth40">操作员</th>
          <th class="opth40">修改时间</th>
          <th class="opth40">操作</th>

      </tr>
  </thead>
  <tbody id="tbodylist">
     <volist name="results" id="lists">
         <tr field='"pgid":"{$lists.pgid}","goodsid":"{$lists.goodsid}","number":"{$lists.number}","saleprice":"{$lists.saleprice}","userprice":"{$lists.userprice}","vipprice":"{$lists.vipprice}","adminuserid":"{$lists.adminuserid}","addtime":"{$lists.addtime}"'>
            <td>{$lists['goods_name']}</td>
            <td><input type="text" num="{$lists['number']}" name="number" value="{$lists['number']|default='1'}"/></td>
            <td><input type="text" saleprice="{$lists['saleprice']}" name="saleprice" value="{$lists['saleprice']}"/></td>
            <td><input type="text" userprice="{$lists['userprice']}" name="userprice" value="{$lists['userprice']}"/></td>
            <td><input type="text" vipprice="{$lists['vipprice']}" name="vipprice" value="{$lists['vipprice']}"/></td>
            <td>{$lists['user_name']|default='-'}</td>
            <td>{$lists['addtime']|default='-'}</td>
            <td>
                <a href="javascript:void(0);" class="btn btn-sm btn-danger" onclick="del(this,{$lists.goodsid})">删除</a>
            </td>
        </tr>
    </volist>
</tbody>
</table>
</div>
<div class="form-group">
    <label class="col-sm-3 control-label">     </label>
    &nbsp;&nbsp;&nbsp;&nbsp;<input class="btn btn-primary btn-success btn-submit" type="button" id="submit" value="提交"/>
    <input class="btn btn-primary" type="button" value="返回" onclick="back();"/>
</div>
</div><!--/porlets-content-->
</div><!--/block-web-->
</div>


</block>
<block name="script">

    <script type="text/javascript" src="__PUBLIC__/Admin/js/json2.js"></script>
    <script type="text/javascript" src="__PUBLIC__/Admin/js/common_manage.js"></script>
    <script type="text/javascript" src="/plugins/laydate/laydate.dev.js"></script>
    <script type="text/javascript" src="/includes/kindeditor/kindeditor-min.js"></script>
    <script type="text/javascript" src="/am/js/validator.js"></script>
    <script type="text/javascript" src="/am/js/tab.js"></script>
<script>

var edit = "{$edit}";
 var sumsaleprice=0;
 var sumuserprice=0;
 var sumvipprice=0;
 var blongtype = "{$blongtype}";
 var datajson ='';

 $("#submit").bind("click",checkdata); 


 var cookiename="goods_{$blongtype}";
 var backurl="{:U('groupList')}";
  var reg=/^\d+(\.\d{0,2})?$/;
       laydate({
           elem: '#start_time',
	    festival: true, //显示节日
	    istime: true,
	    format: 'YYYY-MM-DD hh:mm:ss',
	});
       laydate({
           elem: '#end_time',
	    festival: true, //显示节日
	    istime: true,
	    format: 'YYYY-MM-DD hh:mm:ss',
	});
       function back(){
         setCookie(cookiename,"",-10);
         location.replace("{:U('groupList')}");
     }

     var packageid = $("input[name ='packageid']").val();
     (function($){
        setCookie(cookiename,"",-10);
        $.fn.tabs = function(options){
            var defaults = {
                currentStyle : "current",
                contentList  : "content_list"
            }
            options = $.extend(defaults,options);
            $(this).click(function(){
                $(this).addClass(options.currentStyle).siblings().removeClass(options.currentStyle);
                var _index = $(this).index();
                $("."+options.contentList).eq(_index).show().siblings().hide();
            })
        }
    })(jQuery)    

    $("#nav_des span").tabs({
        currentStyle : "current456",
        contentList  : "con"
    });




    /*layer 弹窗*/
    function showGoodsPics(url,title){
        layer.open({
            type: 2,
            title: title,
            shadeClose: true,
            shade: 0.8,
            area: ['800px', '500px'],
            /*btn: ['关闭窗口'], //按钮*/
            content:url,
        });
    }

    function addgoods(val,url){
   //;
   //$(val).next().click();
    //var url=$(val).attr("url");
    title="添加商品";  
    var mydialog=art.dialog.open(url,{title:title, width:'1200px', height:'80%', opacity: 0.2, id: "add_edit_id",
       ok: function () { 
        this.close();
			//确认商品回调
            fnCreateGoodsList();
            //showgoods(val);
  	       // return false;
        },
        okVal:'确定',
        cancelVal: '取消',
        cancel: function(){this.close();}	
    });
}
   /*var reg = /^[+-]?([0-9]*\.?[0-9]+|[0-9]+\.?[0-9]*)([eE][+-]?[0-9]+)?$/;*/
/*alert($.parseJSON('{$parcelbase}'));*/
$(function(){
    var _list=getCookie(cookiename);
    if(_list){
      fnCreateGoodsList();
  }

  $("input[type='text']").bind("keyup",findtable); 
  $("input[type='number']").bind("keyup",modification_calculation); 
  total_quantity();
})
 //添加修改时，构建商品价格信息，并过滤存在的商品记录
 function fnCreateGoodsList(){

   var ojson=[],lsjson=[],json=[]; 
   var htl="";
    //获取cookie值 
    var _list=getCookie(cookiename);
    if(_list!=""){
      ojson=JSON.parse(_list);
  } 

    //当前已经存在的商品信息 
    $("#tbodylist").find('tr').each(function(){

        var _json=$(this).attr("field");
  /*      if(_json = "undefined"){
          return false;
      }*/
      var _json="{"+_json+"}"
      var tmp =JSON.parse(_json);

  /*      var _price=$(this).children('td').find('input').val();
        if(!isNaN(_price) && reg.test(tmp)){
           tmp.price=_price;
           var _jsonstr=JSON.stringify(tmp);
            _jsonstr=_jsonstr.replace("{","").replace("}","");
           $(this).attr("field",_jsonstr)
       }*/

       if(tmp != ""){
                  lsjson.push(tmp);  //当前特价商品信息
              }
          });
    
    //过滤存在的商品信息 
    for(var i=0;i<ojson.length;i++){
        var flg=false;
        for(var j=0;j<lsjson.length;j++){
            if(ojson[i].goodsid==lsjson[j].goodsid){
                flg=true;
                break;
            }
        }
        if(!flg){json.push(ojson[i]);}
    }
    
     //alert(_list);
     
     if(json.length==0)return;

     for(var i=0;i<json.length;i++){

         /* alert(parcelbase[a]['parcelname']);*/
         htl+='<tr field=\'"pgid":"","goodsid":"'+json[i].goodsid+'","number":"1","saleprice":"'+json[i].saleprice+'","userprice":"'+json[i].userprice+'","vipprice":"'+json[i].vipprice+'","adminuserid":"{adminuserid}","addtime":""\'><td>'+json[i].goodsname+'</td><td><input type="text" num="1" name="number" value="1"></td><td><input type="text" saleprice="'+json[i].saleprice+'" name="saleprice" value="'+json[i].saleprice+'"/></td> <td><input type="text"  userprice="'+json[i].userprice+'" name="userprice" value="'+json[i].userprice+'"/></td><td><input type="text" vipprice="'+json[i].vipprice+'" name="vipprice" value="'+json[i].vipprice+'"/></td><td><span class="unit">{$admin_name}</span></td><td>-</td><td><a href="javascript:void(0);" class="btn btn-sm btn-danger" onclick="del(this,'+json[i].goodsid+')">删除</a></td></tr>';
         sumsaleprice = parseFloat(sumsaleprice)+parseFloat(json[i].saleprice);
         sumuserprice = parseFloat(sumuserprice)+parseFloat(json[i].userprice);
         sumvipprice = parseFloat(sumvipprice)+parseFloat(json[i].vipprice);
     }
     sumsaleprice=parseFloat($("input[name='sprice'").val())+sumsaleprice;
     sumuserprice=parseFloat($("input[name='uprice'").val())+sumuserprice;
     sumvipprice=parseFloat($("input[name='vprice'").val())+sumvipprice;
     getSum(sumsaleprice,sumuserprice,sumvipprice);
     if(htl!=""){
        $("#tbodylist").append(htl); 
        $("input[type='text']").unbind("keyup",findtable);
        $("input[type='text']").bind("keyup",findtable); 

    } 
}
function getSum(sumsaleprice,sumuserprice,sumvipprice){
    $("input[name='sprice'").val(sumsaleprice.toFixed(2));
    $("input[name='uprice'").val(sumuserprice.toFixed(2));
    $("input[name='vprice'").val(sumvipprice.toFixed(2));
}
function del($_this,goodsid){
 if(confirm("确定删除这条记录？"))
 {
  $_this=$($_this);
  var number=0;
  var saleprice=0;
  var userprice=0;
  var vipprice=0;
      //获取cookie值 

      var _list=getCookie(cookiename);
      if(_list!=""){
          var ojson=JSON.parse(_list),json=[]; 
		    //删除cookie里的商品信息 

          for(var i=0;i<ojson.length;i++){
            if(ojson[i].goodsid==goodsid){
                continue;
            }
            json.push(ojson);
        }
        setCookie(cookiename,"",-10);
        if(json.length>0){
            var _db=JSON.stringify(json);
            setCookie(cookiename,_db,1);
		   //删除本tr ,总价格
       } 
   }

   var $_list = $_this.parents("tr").find("td");
   var arr = new Array();
   $_list.each(function(i){

    var $_input = $_list.eq(i).find("input").val();

    if(!isNaN($_input)){

       arr.push($_input);	
   }
});
   saleprice=arr[0]*arr[1];
   userprice=arr[0]*arr[2];
   vipprice=arr[0]*arr[3];
   saleprice=parseFloat($("input[name='sprice'").val())-saleprice;
   userprice=parseFloat($("input[name='uprice'").val())-userprice;
   vipprice=parseFloat($("input[name='vprice'").val())-vipprice;
   getSum(saleprice,userprice,vipprice);
   $_this.parents("tr").remove();

}
}
function give(){

 var $_list = $_this.parents("tr").find("td");
 var arr = new Array();
 $_list.each(function(i){

    var $_input = $_list.eq(i).find("input").val();

    if(!isNaN($_input)){

       arr.push($_input);	
   }
})
}
var _time=0;
function  findtable(){
 clearTimeout(_time);
 $_this = $(this);
 _time=setTimeout(function(){searchtable($_this);},300);
}
//计算总价
function searchtable($_this)
{

	var sumsaleprice=0;
    var sumuserprice=0;
    var sumvipprice=0;
    //修改商品数量，三个总价都变化
    if($_this.attr('name') =='number'){
      var number = $_this.val();
      var old_number = $_this.attr("num");
      if(number == old_number)
      {
         return ;
     }
     var saleprice = $_this.parents("td").next().find("input").val();
     var userprice = $_this.parents("td").next().next().find("input").val();
     var vipprice = $_this.parents("td").next().next().next().find("input").val();
     if(!reg.test(number)){
      alert('数量输入有误');
      $_this.val(old_number);
      return false;
  }
  if(number<=0){
    $_this.val(old_number);
    return false;
}
if(number.length >= 8){
    alert('数量输入有误');
    $_this.val(old_number);
    return false;
}
sumsaleprice=parseFloat($("input[name='sprice']").val())-parseFloat(saleprice*old_number);
sumuserprice=parseFloat($("input[name='uprice']").val())-parseFloat(userprice*old_number);
sumvipprice=parseFloat($("input[name='vprice']").val())-parseFloat(vipprice*old_number);
		 // if(number > 1)
		  //{
            sumsaleprice=sumsaleprice+parseFloat(saleprice*number);
            sumuserprice=sumuserprice+parseFloat(userprice*number);
            sumvipprice=sumvipprice+parseFloat(vipprice*number);

		 // }

         getSum(sumsaleprice,sumuserprice,sumvipprice);
         $_this.attr("num",number);
     }
     if($_this.attr('name') =='saleprice'){
      var price = $_this.val();
      var old_price = $_this.attr("saleprice");
      if(price == old_price)
      {
         return ;  
     }
     var number = $_this.parent("td").prev().find("input").val();
     if(!reg.test(price)|| !reg.test(number)){
        alert('价格输入有误');
        $_this.val(old_price);
        return false;
    }
    if(price <=0|| number<=0){
     $_this.val(old_price);
     return false;
 }
 if(price.length >= 8|| number.length >= 8){
    alert('价格输入有误');
    $_this.val(old_price);
    return false;
}
sumsaleprice=parseFloat($("input[name='sprice']").val())-parseFloat(old_price*number);
sumsaleprice=sumsaleprice+parseFloat(price*number);	
$("input[name='sprice']").val(sumsaleprice.toFixed(2));
$_this.attr("saleprice",price);
}
if($_this.attr('name') =='userprice'){
  var price = $_this.val();
  var old_price = $_this.attr("userprice");

  if(price == old_price)
  {
     return ;  
 }
 var number = $_this.parent("td").prev().prev().find("input").val();
 if(!reg.test(price)|| !reg.test(number)){
    alert('价格输入有误');
    $_this.val(old_price);
    return false;
}
if(price <=0|| number<=0){
   $_this.val(old_price);
   return false;
}
if(price.length >= 8|| number.length >= 8){
    alert('价格输入有误');
    $_this.val(old_price);
    return false;
}
sumuserprice=parseFloat($("input[name='uprice']").val())-parseFloat(old_price*number);
sumuserprice=sumuserprice+parseFloat(price*number);	
$("input[name='uprice']").val(sumuserprice.toFixed(2));
$_this.attr("userprice",price);
}
if($_this.attr('name') =='vipprice'){
  var price = $_this.val();
  var old_price = $_this.attr("vipprice");
  if(price == old_price)
  {
     return ;  
 }
 var number = $_this.parent("td").prev().prev().prev().find("input").val();
 if(!reg.test(price)|| !reg.test(number)){
    alert('价格输入有误');
    $_this.val(old_price);
    return false;
}
if(price <=0|| number<=0){
   $_this.val(old_price);
   return false;
}
if(price.length >= 8|| number.length >= 8){
    alert('价格输入有误');
    $_this.val(old_price);
    return false;
}
sumvipprice=parseFloat($("input[name='vprice']").val())-parseFloat(old_price*number);
sumvipprice=sumvipprice+parseFloat(price*number);	
$("input[name='vprice']").val(sumvipprice.toFixed(2));
$_this.attr("vipprice",price);
}

}
function  getdatalist(){
   var lsjson=[];
   //当前已经存在的商品信息 
   ;
   $("#tbodylist").children('tr').each(function(){
    var _json=$(this).attr("field");
    var _json="{"+_json+"}"
    var tmp =JSON.parse(_json);
    var _number=$(this).children('td').eq("1").find('input').val();
    var _saleprice=$(this).children('td').eq("2").find('input').val();
    var _userprice=$(this).children('td').eq("3").find('input').val();
    var _vipprice=$(this).children('td').eq("4").find('input').val();

    if(reg.test(_saleprice) && reg.test(_number)){
     tmp.saleprice=_saleprice;
     tmp.userprice=_userprice;
     tmp.vipprice=_vipprice;
     tmp.number=_number;
 }
        //价格大于0才添加，否则删除信息。
        if(parseInt(_saleprice)>0&&parseInt(_number)>0){
          lsjson.push(tmp);  //当前特价商品信息
      }
  });
   ;
   return lsjson;   
}


 //检查数据是否符合条件
 function  checkdata(){ 
     debugger;
     var blongtype=$("#select").val();
     var packagename=$("input[name='packagename']").val();
     var total=$("input[name='total']").val();
     var starttime=$("input[name='starttime']").val();
     var endtime=$("input[name='endtime']").val();

     // 判断包的数量
     var number = $("input[name ='total']").val();
     var multiple = $("input[name ='multiple']").val();
     var maxnumber = $("input[name ='maxnumber']").val();
     var groupnumber = $("input[name ='groupnumber']").val();
     var totalquantity=  $("input[name ='totalquantity']").val();

     var minnumber = $("input[name ='minnumber']").val();




     if(minnumber == ""){
         minnumber = 0;
     }
     if(maxnumber == ""){
         maxnumber = 0;
     }

     if(maxnumber > 0 ){
         if(parseInt(minnumber)  > parseInt(maxnumber) ){
          art.dialog({title:'温馨提示',content: '最小购买数量不能大于最大购买数量', ok: function () {this.close();return false;},okval:'确定'}); 
           return;
         }

     }

     if(number ==0 || number ==""){
       art.dialog({title:'温馨提示',content: '请填写组团人数', ok: function () {this.close();return false;},okval:'确定'}); 
       return;
   }
   var multiple = $("input[name ='multiple']").val();
   if(multiple ==0 || multiple ==""){
       art.dialog({title:'温馨提示',content: '请填写包倍数', ok: function () {this.close();return false;},okval:'确定'}); 
       return;
   }
   var maxnumber = $("input[name ='maxnumber']").val();
   if(maxnumber <0 || maxnumber ==""){
       art.dialog({title:'温馨提示',content: '请填写最大数量', ok: function () {this.close();return false;},okval:'确定'}); 
       return;
   }
   var groupnumber = $("input[name ='groupnumber']").val();
   if(groupnumber ==0 || groupnumber ==""){
       art.dialog({title:'温馨提示',content: '请填写组团总个数', ok: function () {this.close();return false;},okval:'确定'}); 
       return;
   }


   if(packagename==""){
       art.dialog({title:'温馨提示',content: '请填写包名称', ok: function () {this.close();return false;},okval:'确定'}); 
       return false;
   } 
   if(total==""){
       art.dialog({title:'温馨提示',content: '请输入组团人数', ok: function () {this.close();return false;},okval:'确定'}); 
       return false;
   } 
   if(starttime==""){
       art.dialog({title:'温馨提示',content: '请选择开始时间', ok: function () {this.close();return false;},okval:'确定'}); 
       return false;
   } 
   if(endtime==""){
       art.dialog({title:'温馨提示',content: '请选择结束时间', ok: function () {this.close();return false;},okval:'确定'}); 
       return false;
   } 

   datajson= getdatalist();

   if(!datajson|| datajson.length==0){
    art.dialog({title:'温馨提示',content: '没有任何商品信息，请添加商品或者设置价格!', ok: function () {this.close();return false;},okval:'确定'});  
    return false;
} 


if(blongtype!="" && blongtype!=blongtype){

   art.dialog({
    title:'温馨提示',
    content: '包类型与当前选中的包类型不一致，是否继续添？',
    ok: function () { 
        _flg=true;
        salesave();
        this.close();
        return false;
    },
    cancelVal: '关闭',
                cancel: true //为true等价于function(){}
            }); 
}else{

  _flg=true;

  salesave(datajson); 
} 
}


  //提交数据保存特价商品信息，检测记录信息
  function  salesave(datajson)
  {
   
    if(!_flg||!datajson){return false;}
      var postdata=JSON.stringify(datajson);
  
    /*var _purchase=$("#purchase").val();*/
    var url="{:U('doGroup')}";
  var datas=$("#form_table").serializeArray();
    debugger;
    $.ajax({
       'url': url,
       'data': {data:datas,json:postdata},
       'dataType': 'json',
       'type': 'POST',
       success: function (data) {

           if(!data){
               art.dialog({title:'温馨提示',content: '提交数据保存失败', ok: function () {this.close();return false;},okval:'确定'});
               return;
           }

           art.dialog({title:'温馨提示',content: data.msg, ok: function () {this.close();return false;},okval:'确定'});

           if (data.staute =="success") {  
                 setCookie(cookiename,"",-10); //清理cookie信息
                 location.replace(backurl);
             }

         }, error: function (err) { 

           art.dialog({title:'温馨提示',content: err.responseText, ok: function () {this.close();return false;},okval:'确定'});
       },complete: function () {

       }
   });  
}

function setCookie(c_name, value, expiredays){
    　　　var exdate=new Date();
    　　　exdate.setDate(exdate.getDate() + expiredays);
    　　　document.cookie=c_name+ "=" + escape(value) +";path=/;domain="+document.domain+";"+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}



function getCookie(c_name){
    　　　　if (document.cookie.length>0){　　//先查询cookie是否为空，为空就return ""
    　　　　　　c_start=document.cookie.indexOf(c_name + "=")　　//通过String对象的indexOf()来检查这个cookie是否存在，不存在就为 -1　　
　　　　　　if (c_start!=-1){ 
    　　　　　　　　c_start=c_start + c_name.length+1　　//最后这个+1其实就是表示"="号啦，这样就获取到了cookie值的开始位置
    　　　　　　　　c_end=document.cookie.indexOf(";",c_start)　　//其实我刚看见indexOf()第二个参数的时候猛然有点晕，后来想起来表示指定的开始索引的位置...这句是为了得到值的结束位置。因为需要考虑是否是最后一项，所以通过";"号是否存在来判断
    　　　　　　　　if (c_end==-1) c_end=document.cookie.length
    　　　　　　　　return unescape(document.cookie.substring(c_start,c_end))　　//通过substring()得到了值。想了解unescape()得先知道escape()是做什么的，都是很重要的基础，想了解的可以搜索下，在文章结尾处也会进行讲解cookie编码细节
　　　　　　} 
　　　　}
　　　　return "";
}

 	/***
 * 图片数组 生成选择图片预览
 * @param data_arry  图片数据数组
 * @param data_arry_length 图片数据数组长度
 * @private
 */
 function _getDetailsPic(data_arry,data_arry_length,only_choose_one,dom_id,is_need_watch_pic){
    //<div class="pics_wrp js_guige_images_unitymain">
    //    <div class="edit_pic_wrp">
    //        <img src="/Public/Admin/themes/images/img14.png">
    //
    //        <div class="edit_pic_mask">
    //         <a href="javascript:;" class="icon18_common del_gray js_delete"></a>
    //        </div>
    //    </div>
    //</div>
    var _dom_id= dom_id;
    
    for(var i=0;i<data_arry_length;i++){
        dom_id = _dom_id;
        var img_src = data_arry[i]['src'];
        var img_id  = data_arry[i]['id'];
        var haveSelected_len = $('input[name=is_first]:checked').length;
        var _checked='';
        if( haveSelected_len === 0 ){
            _checked='checked';
        }

        var hide_style='';
        if(typeof  only_choose_one !=='undefined' && only_choose_one.length!==0){
            hide_style=' style="display:none;" ';
        }

        var id ="file_"+img_id;

        var pic_name='pic[]';
        if(typeof dom_id === 'undefined' || dom_id.length===0  ){
            if($('#'+$.trim(id)).length>0)continue;
            dom_id='.upload_preview';
        }else{
            if($('#'+dom_id+' #'+$.trim(id)).length>0)continue;
            pic_name=dom_id+'_pic[]';
            dom_id='#'+dom_id;
        }
        console.log(img_src);
        var btn_del = '<a href="javascript:;" title="点击移除" class="icon18_common del_gray js_delete" onclick="removeThisSelected(this);"></a>';
        var btn_watch = '';
        if( typeof(is_need_watch_pic) !== 'undefined' || is_need_watch_pic.length == 0 ){
            var img_path = img_src.replace('/attas/orgimg/','');
            img_path = img_path.replace('/attas/','');
            btn_watch ='<a href="'+img_path+'" title="查看原图" target="_blank" class="icon18_common search_gray js_delete"></a>';
        }


        var _pic_html='<div class="pics_wrp js_guige_images_unitymain" style="height: 247px;" id="'+$.trim(id)+'" >' +
        '<div class="edit_pic_wrp" style="width: 200px;max-width:200px;height: 200px;">';
        _pic_html+='<img src="'+img_src+'">';
        _pic_html+='<div class="edit_pic_mask">' + btn_del + btn_watch +
        '<input type="hidden" name="'+pic_name+'" value="'+img_id+'" />' +
        '</div>' +
        '</div>' +
        '<div class="gallery_img_sort">'+
        '<label>排序：</label>'+
        '<input type="text"  name="img_'+img_id+'_sort" value="">'+
        '</div>'+
        '</div>';

        if(typeof  only_choose_one !=='undefined' && only_choose_one.length!==0 ){

            $(dom_id).html(_pic_html);
        }else{

            $(dom_id).append(_pic_html);
        }

    }
}

/**
 * 移除选中的图片
 * @param obj
 */
 function removeThisSelected(obj){
    //询问框
    layer.confirm('您确定要移除吗?', {
        btn: ['确定','取消'] //按钮
    }, function(){
        /*layer.msg('的确很重要', {icon: 1});*/
        $(obj).parent().parent().parent().remove();
        //先移除，通过ajax后台请求控制器改变data_id;
        /*$.ajax({
         url:_data_id_url,
         data:{'id':$(obj).find('input').val()},
         type:'POST',
         dataType:'json',
         success:function(data){
         $(obj).parent().parent().remove();
         },
         error:function(){

         },complete:function(){

         }
     });*/
    layer.closeAll();
}, function(){
        /*layer.msg('也可以这样', {
         time: 20000, //20s后自动关闭
         btn: ['明白了', '知道了']
     });*/
    layer.closeAll();
});
}



/**
 * 移除选中的图片
 * @param obj
 */
 function removeThisImg(obj,img_id){
    //询问框

    layer.confirm('您确定要移除吗?', {
        btn: ['确定','取消'] //按钮
    }, function(){
        /*layer.msg('的确很重要', {icon: 1});*/
        $(obj).parent().parent().parent().remove();
        //先移除，通过ajax后台请求控制器改变data_id;
        $.ajax({
           url:"{:U('delete_img')}",
           data:{'img_id':img_id},
           type:'POST',
           dataType:'json',
           success:function(data){

           },
           error:function(){

           },complete:function(){

           }
       });
        layer.closeAll();
    }, function(){
        /*layer.msg('也可以这样', {
         time: 20000, //20s后自动关闭
         btn: ['明白了', '知道了']
     });*/
    layer.closeAll();
});
}





//计算默认包倍数
function total_quantity(){

    var packageid = $("input[name ='packageid']").val();
    var number = $("input[name ='total']").val();
    var minnumber = $("input[name ='minnumber']").val();
    var multiple = $("input[name ='multiple']").val();
    var maxnumber = $("input[name ='maxnumber']").val();
    var groupnumber = $("input[name ='groupnumber']").val();
    var totalquantity=  $("input[name ='totalquantity']").val();
    if(blongtype=="presell"){
        var maxnumber = $("input[name ='minnumber']").val();
    }else{
        if(maxnumber ==0 || maxnumber ==""){
           var maxnumber = $("input[name ='minnumber']").val();
       } 
   }
   if(packageid ==""){

    var totalquantity = number*multiple*maxnumber*groupnumber;
    $("input[name ='totalquantity']").val(totalquantity);
    return;
}
var multiple = totalquantity/number/maxnumber/groupnumber;
$("input[name ='multiple']").val(multiple);
}


//修改后计算

function modification_calculation(){
 var number = $("input[name ='total']").val();
 if(number ==0 || number ==""){

   return;
}
var multiple = $("input[name ='multiple']").val();
if(multiple ==0 || multiple ==""){

   return;
}
       //如果是添加预售的就按最小的数量计算，如果是团购就按最大的计算（如果最大为0  就按最小计算）
       if(blongtype =="presell"){
          var maxnumber = $("input[name ='minnumber']").val();
      }else{
         var maxnumber = $("input[name ='maxnumber']").val();
         if(maxnumber ==0 || maxnumber ==""){
           var maxnumber = $("input[name ='minnumber']").val();
       }
   }

   var groupnumber = $("input[name ='groupnumber']").val();
   if(groupnumber ==0 || groupnumber ==""){

       return;
   }
   var totalquantity = number*multiple*maxnumber*groupnumber;
   $("input[name ='totalquantity']").val(totalquantity);
}
</script>

</block>
